package com.bogu.activity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.MenuItem;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.PopupMenu;
import android.widget.ProgressBar;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;

import com.bogu.adapter.BiologyAdapter;
import com.bogu.adapter.SearchAdapter;
import com.bogu.dao.BiologyDao;
import com.bogu.model.Biology;
import com.bogu.model.Category;
import com.bogu.model.Field;
import com.bogu.model.Record;


import com.example.boguplatform.R;
import com.lidroid.xutils.DbUtils;
import com.lidroid.xutils.db.sqlite.Selector;
import com.lidroid.xutils.exception.DbException;
import com.xuan.tuya.BasicActivity;
import com.xuan.tuya.InjectView;

public class SearchActivity extends BasicActivity implements
		View.OnClickListener {
	private int type_id;
	private ArrayList<Field> fields;
	@InjectView(R.id.search)
	private Button search;
	@InjectView(R.id.content)
	private EditText content;
	private PopupMenu popup;
	@InjectView(R.id.list)
	private ListView listView;
	@InjectView(R.id.progressBar)
	private ProgressBar progressBar;
	@InjectView(R.id.spinner)
	private Spinner spinner;

	@InjectView(R.id.history)
	private TextView history;
	@InjectView(R.id.history_line)
	private View history_line;
	@InjectView(R.id.clear)
	private Button clear;
	@InjectView(R.id.hint)
	private TextView hint;
	private DbUtils dbUtils;
	private String selection = "all";
	private BiologyDao biologyDao;

	ArrayAdapter<String> fieldAdapter = null;

	private int p;
	private String field_name;
	private ArrayList<Category> categories;
	private ArrayList<Biology> biologies;
	private ArrayList<String> items0;
	private HashMap<Integer, ArrayList<String>> items1;
	private ArrayList<String> items2;
	private boolean issearch = false;
	
	List<Record> records;
	SearchAdapter adapter;
	private Handler handler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			// TODO 自动生成的方法存根
			super.handleMessage(msg);
			switch (msg.what) {

			case 1:
				progressBar.setVisibility(View.GONE);
				biologies = (ArrayList<Biology>) msg.obj;
				if(biologies.size()==0){
					hint.setVisibility(View.VISIBLE);
					hint.setHint("未找到与\""+content.getText().toString()+"\"相关的内容");
				}else{
					hint.setVisibility(View.GONE);
					
				}
				BiologyAdapter adapter = new BiologyAdapter(
						SearchActivity.this, biologies);
				listView.setAdapter(adapter);
				history.setVisibility(View.GONE);
				history_line.setVisibility(View.GONE);
				clear.setVisibility(View.GONE);
				progressBar.setVisibility(View.GONE);
			
						listView.setOnItemClickListener(new OnItemClickListener() {

							@Override
							public void onItemClick(AdapterView<?> parent, View view,
									int position, long id) {
								// TODO 自动生成的方法存根
								Intent intent=new Intent(SearchActivity.this,BiologyDetailActivity.class);
								intent.putExtra("biology", biologies.get(position));
								intent.putExtra("position", position);
								BiologyDao biologyDao=new BiologyDao(SearchActivity.this,null);
								biologyDao.updateClick(biologies.get(position).getId());
								startActivityForResult(intent, 0);
							}
						});
				
				break;
			case 3:
				progressBar.setVisibility(View.VISIBLE);
				break;

			case 5:
				progressBar.setVisibility(View.GONE);
				break;
			case 10:
				history.setVisibility(View.GONE);
				history_line.setVisibility(View.GONE);

				break;

			}
		}

	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO 自动生成的方法存根
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_search);
		type_id = getIntent().getIntExtra("type_id", 0);
		fields = (ArrayList<Field>) getIntent().getExtras().get("fields");
		setSpinner();
		biologyDao = new BiologyDao(this, handler);
        clear.setOnClickListener(this);
		search.setOnClickListener(this);
		initActionBar();
		records = new ArrayList<Record>();
		dbUtils = DbUtils.create(this, "record.db");

		try {

			records = dbUtils.findAll(Selector.from(Record.class));
		} catch (DbException e) {
			// TODO 自动生成的 catch 块
			e.printStackTrace();
		}
		if (records != null) {
			final ArrayList<String> items = new ArrayList<String>();
			for (int i = records.size() - 1 > 9 ? 9 : records.size() - 1; i >= 0; i--) {
				items.add(records.get(i).getContent());
			}
			adapter = new SearchAdapter(items, this, dbUtils,
					handler);
			listView.setAdapter(adapter);
			listView.setOnItemClickListener(new OnItemClickListener() {

				@Override
				public void onItemClick(AdapterView<?> parent, View view,
						int position, long id) {
					// TODO 自动生成的方法存根
					biologyDao.getBiology(type_id, field_name,
							items.get(position));
					issearch = true;
					content.setText(items.get(position));
					content.setSelection(items.get(position).length());
					Record record0;
					try {
						record0 = dbUtils.findFirst(Selector.from(Record.class)
								.where("content", "=", items.get(position)));

						if (record0 != null) {
							dbUtils.delete(record0);
						}

						Record record = new Record();
						record.setContent(items.get(position));
						dbUtils.save(record);
					} catch (DbException e) {
						// TODO 自动生成的 catch 块
						e.printStackTrace();
					}

				}
			});
			clear.setVisibility(View.VISIBLE);
		} else {
			history.setVisibility(View.GONE);
			history_line.setVisibility(View.GONE);
            clear.setVisibility(View.GONE);
		}

		Timer timer = new Timer();

		timer.schedule(new TimerTask()

		{

			public void run()

			{

				InputMethodManager inputManager =

				(InputMethodManager) content.getContext().getSystemService(
						Context.INPUT_METHOD_SERVICE);

				inputManager.showSoftInput(content, 0);

			}

		},

		998);
	}

	private void setSpinner() {
		items0 = new ArrayList<String>();
		items1 = new HashMap<Integer, ArrayList<String>>();

		field_name = fields.get(0).getField_name();
		items2 = new ArrayList<String>();
		for (int i = 0; i < fields.size(); i++) {
			items2.add(fields.get(i).getTitle());
		}

		fieldAdapter = new ArrayAdapter<String>(this,
				android.R.layout.simple_spinner_dropdown_item ,items2);

		spinner.setAdapter(fieldAdapter);

		spinner.setSelection(0, true);

		spinner.setOnItemSelectedListener(new OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> parent, View view,
					int position, long id) {
				// TODO 自动生成的方法存根
				field_name = fields.get(position).getField_name();
				if (issearch) {
					if (!content.getText().toString().equals("")) {
						biologyDao.getBiology(type_id, field_name, content
								.getText().toString());
					} else {
						Toast.makeText(SearchActivity.this, "请输入搜索内容",
								Toast.LENGTH_SHORT).show();
					}
				}
			}

			@Override
			public void onNothingSelected(AdapterView<?> parent) {
				// TODO 自动生成的方法存根

			}
		});
	}

	private void initActionBar() {

		getSupportActionBar().setHomeButtonEnabled(true);
		getSupportActionBar().setDisplayShowTitleEnabled(true);
		getSupportActionBar().setDisplayUseLogoEnabled(false);
		getSupportActionBar().setDisplayShowHomeEnabled(false);
		getSupportActionBar().setDisplayShowCustomEnabled(true);
		getSupportActionBar().setDisplayHomeAsUpEnabled(true);
		getSupportActionBar().setTitle("搜索");
	}

	@Override
	public void onClick(View v) {
		// TODO 自动生成的方法存根
		switch (v.getId()) {
		case R.id.search:

			if (!content.getText().toString().equals("")) {
				issearch = true;

				try {
					System.out.println(content.getText().toString());
					String search = content.getText().toString();
					Record record0 = dbUtils.findFirst(Selector.from(
							Record.class).where("content", "=", search));
					if (record0 != null) {
						dbUtils.delete(record0);
					} else if (dbUtils.findAll(Selector.from(Record.class)) != null) {
						if (dbUtils.findAll(Selector.from(Record.class)).size() == 10) {
							List<Record> records = dbUtils.findAll(Selector
									.from(Record.class));
							dbUtils.delete(records.get(0));
						}
					}

					Record record = new Record();
					record.setContent(content.getText().toString());
					dbUtils.save(record);
				} catch (DbException e) {
					// TODO 自动生成的 catch 块
					e.printStackTrace();
				}
				biologyDao.getBiology(type_id, field_name, content.getText()
						.toString());
			} else {
				Toast.makeText(this, "请输入搜索内容", Toast.LENGTH_SHORT).show();

			}
			break;
		case R.id.clear:
			try {
				dbUtils.dropTable(Record.class);
				
			   
			    listView.setAdapter(null);
			    clear.setVisibility(View.GONE);
			    history.setVisibility(View.GONE);
				history_line.setVisibility(View.GONE);

			} catch (DbException e) {
				// TODO 自动生成的 catch 块
				e.printStackTrace();
			}
			break;
		}
	}

	@Override
	protected void onActivityResult(int arg0, int arg1, Intent arg2) {
		// TODO 自动生成的方法存根
		switch (arg1) {
		case RESULT_OK:
			Bundle b = arg2.getExtras();
			int position = b.getInt("position");
			int plus = b.getInt("plus");
			biologies.get(position).setComment_count(
					biologies.get(position).getComment_count() + plus);
			break;
		}
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// TODO 自动生成的方法存�?
		switch (item.getItemId()) {
		case android.R.id.home:
			finish();
			break;

		}
		return super.onOptionsItemSelected(item);
	}
}
